package cn.b.sky.user;

import cn.b.sky.user.enums.ResourceTypeCode;
import cn.b.sky.user.service.SecurityService;
import cn.b.sky.user.service.model.MenuUrl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service("securityMetadataSource")
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private static Map<String, Collection<ConfigAttribute>> urlPermissions = null;

    @Resource
    private SecurityService securityService;

    private RequestMatcher requestMatcher; // 匹配规则

    /**
     * 加载所有url所对应的菜单权限信息
     */
    private void loadUrlPermissions() {
        urlPermissions = new HashMap<String, Collection<ConfigAttribute>>();
        // 查询类型为form的菜单，这类菜单需要过滤url
        List<MenuUrl> menus = this.securityService.listMenuUrl(ResourceTypeCode.FORM.getValue());
        if (null != menus) {
            for (MenuUrl item : menus) {
                String url = item.getWebUrl();
                if (null != url && !"".equals(url)) {
                    if (!urlPermissions.containsKey(url)) {
                        urlPermissions.put(url, new ArrayList<ConfigAttribute>());
                    }
                    urlPermissions.get(url).add(new SecurityConfig(Constants.ROLEPREFIX + item.getMenuCode()));

                }
            }
        }

    }

    /**
     * 返回指定的url所对应的菜单权限信息
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) {
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        if (urlPermissions == null) {
            loadUrlPermissions();
        }
        Collection<ConfigAttribute> authoritys = new ArrayList<ConfigAttribute>();
        for (String url : urlPermissions.keySet()) {
            if (StringUtils.isBlank(url)) {
                continue;
            }
            requestMatcher = new AntPathRequestMatcher(url);
            if (requestMatcher.matches(request) && urlPermissions.get(url) != null) {
                authoritys.addAll(urlPermissions.get(url));
            }
        }
        return authoritys;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }
}
